package org.smart4j.framework.bean;

import org.apache.commons.lang3.StringUtils;
import org.smart4j.framework.util.CastUtil;
import org.smart4j.framework.util.CollectionUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author djw
 * @time 2017/10/24 16:36
 */
public class Param {

    private List<FormParam> formParamList;
    private List<FileParam> fileParamList;

    public Param(List<FormParam> formParams){
        this.formParamList=formParams;
    }
    public Param(List<FormParam> formParams,List<FileParam> fileParams){
        this.formParamList=formParams;
        this.fileParamList=fileParams;
    }

    public Map<String,Object> getFieldMap(){
        Map<String,Object> fieldMap=new HashMap<>();
        if(CollectionUtil.isNotEmpty(formParamList)){
            for(FormParam formParam:formParamList){
                String fieldName=formParam.getFieldName();
                Object fieldValue=formParam.getFieldValue();
                if(fieldMap.containsKey(fieldName)){
                    fieldValue=fieldMap.get(fieldName)+ "&"+fieldValue;
                }
                fieldMap.put(fieldName,fieldValue);
            }
        }
        return fieldMap;
    }

    public Map<String,List<FileParam>> getFileMap(){
        Map<String,List<FileParam>> fileMap=new HashMap<>();
        if(CollectionUtil.isNotEmpty(fileParamList)){
            for(FileParam fileParam:fileParamList){
                String fieldName=fileParam.getFieldName();
                List<FileParam> fileList;
                if(fileMap.containsKey(fieldName)){
                    fileList=fileMap.get(fieldName);
                }else {
                    fileList=new ArrayList<>();
                }
                fileList.add(fileParam);
                fileMap.put(fieldName,fileList);
            }
        }
        return fileMap;
    }

    public List<FileParam> getFileList(String fieldName){
        return (List<FileParam>) getFieldMap().get(fieldName);
    }
    public FileParam getFile(String fieldName){
        List<FileParam> fileParamList=getFileList(fieldName);
        if(CollectionUtil.isNotEmpty(fileParamList) && fileParamList.size()==1){
            return fileParamList.get(0);
        }
        return null;
    }

    public boolean isEmpty(){
        return CollectionUtil.isEmpty(formParamList) && CollectionUtil.isNotEmpty(fileParamList);
    }
    public String getString(String name){
        return CastUtil.castString(getFieldMap().get(name));
    }
    public double getDouble(String name){
        return CastUtil.castDouble(getFieldMap().get(name));
    }
    public long getLong(String name){
        return CastUtil.castLong(getFieldMap().get(name));
    }

    public int getInt(String name){
        return CastUtil.castInt(getFieldMap().get(name));
    }
    public boolean getBoolean(String name){
        return CastUtil.castBoolean(getFieldMap().get(name));
    }
}
